// 问题：在基础功能上，我们发现：
//      当遇到异步逻辑执行并改变了状态status后，如何让then()能接收到回调函数？

// 解决：
//      1. 添加保存回调函数的属性 onFulfilledCallback 和 onRejectedCallback
//      2. 将注册的回调函数进行缓存，缓存至 onFulfilledCallback 和 onRejectedCallback 中
//      3. 当resolve或reject的时候， 再执行缓存的回调函数 onFulfilledCallback 或 onRejectedCallback

const PENDING = 'pending'
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'

/**
 *
 *
 * @class MyPromise
 */
class MyPromise {
    constructor(executor) {
        executor(this.resolve, this.reject)
    }
    status = PENDING

    value = null
    reason = null

    // 1. 添加属性，用以存储 then() 的回调函数
    onFulfilledCallback = null
    onRejectedCallback = null

    resolve = (value) => {
        if (this.status === PENDING) {
            this.status = FULFILLED
            this.value = value
            // 3. 当调用成功函数时，此时将缓存的回调函数取出来，进行调用
            this.onFulfilledCallback && this.onFulfilledCallback(this.value)
        }
    }
    reject = (reason) => {
        if (this.status === PENDING) {
            this.status = REJECTED
            this.reason = reason
            // 3. 当调用成功函数时，此时将缓存的回调函数取出来，进行调用
            this.onRejectedCallback && this.onRejectedCallback(this.reason)
        }
    }

    then = (onFulfilled, onRejected) => {
        if (this.status === FULFILLED) {
            onFulfilled(this.value)
        }
        else if (this.status === REJECTED) {
            onRejected(this.reason)
        } 
        else {  // this.status === `Pending`
            // 2. 当当前状态为Pending时，则将业务注册的回调函数进行缓存。以便业务在调用了 resolve() 或 reject() 时，再取出来调用
            this.onFulfilledCallback = onFulfilled
            this.onRejectedCallback = onRejected
        }
    }
}

console.log(`--------------- 处理异步逻辑 ------------------`)
const promise = new MyPromise((resolve, reject) => {
    setTimeout(() => {
        // resolve(`resolve: success`)
        reject(`reject: err`)
    }, 0);
})
promise.then((value) => {
    console.log(value)
},
(reason) => {
    console.log(reason)
})

console.log(`--------------- 调用多次then() ------------------`)
const promise1 = new MyPromise((resolve, reject) => {
    setTimeout(() => {
        resolve(`resolve: success`)
        // reject(`reject: err`)
    }, 0);
})
promise1.then((value) => {
    console.log(`我是第1个then()`)
    console.log(value)
},
(reason) => {
    console.log(`我是第1个then()`)
    console.log(reason)
})

promise1.then((value) => {
    console.log(`我是第2个then()`)
    console.log(value)
},
(reason) => {
    console.log(`我是第2个then()`)
    console.log(reason)
})

promise1.then((value) => {
    console.log(`我是第3个then()`)
    console.log(value)
},
(reason) => {
    console.log(`我是第3个then()`)
    console.log(reason)
})

// 此时，出现新的问题，当执行多次then()时，只有最后这个then()的回调函数生效了，第1个和第2个then()的回调函数并没有打印
// 问题：如何所有的then()中的回调函数都能有效